/**
 * 
 */
package com.ubo.visu.model;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javafx.scene.Group;

import com.ubo.visu.painter.association.IAssociationPainter;
import com.ubo.visu.painter.association.LineAssociationPainter;
import com.ubo.visu.painter.node.INodePainter;
import com.ubo.visu.painter.node.RectangleNodePainter;
import com.ubo.visu.util.FxUtil;

/**
 * @author saludegu
 * 
 */
public class ModelGraph {

	/**
	 * Set des nodes contenus dans le graphe.
	 */
	protected Set<ModelNode> mNodesSet;

	/**
	 * Set des associations contenues dans le graphe.
	 */
	protected Set<ModelAssociation> mAssociationsSet;

	/**
	 * Groupe principal.
	 */
	protected Group mMainGroup;

	/**
	 * Compteur de lignes.
	 */
	protected int cptRow = 1;

	/**
	 * Compteur de colonnes.
	 */
	protected int cptColumn;

	/**
	 * 
	 * Constructor
	 * 
	 */
	public ModelGraph() {
		mNodesSet = new HashSet<ModelNode>();
		mAssociationsSet = new HashSet<ModelAssociation>();
		mMainGroup = new Group();
	}

	/**
	 * Ajout d'un node.
	 * 
	 * @param newNode
	 */
	public void addModelNode(ModelNode newNode) {
		mNodesSet.add(newNode);
	}

	/**
	 * Ajout d'une association.
	 * 
	 * @param association
	 */
	public void addAssociatioNode(ModelAssociation association) {
		mAssociationsSet.add(association);
	}

	/**
	 * 
	 * @return
	 */
	public Group paintGraph() {
		Map<ModelNode, INodePainter> mPaintersMap = new HashMap<ModelNode, INodePainter>();
		int cpt = 0;
		for (final ModelNode node : mNodesSet) {
			final INodePainter painter = new RectangleNodePainter();
			node.paint(painter);
			mPaintersMap.put(node, painter);
			painter.getContent().setLayoutX((cpt) * 200);
			painter.getContent().setLayoutY((cpt) * 50);
			cpt++;
			FxUtil.runOnFx(new Runnable() {

				@Override
				public void run() {
					mMainGroup.getChildren().add(painter.getContent());
				}
			});
		}
		for (ModelAssociation association : mAssociationsSet) {
			final IAssociationPainter painter = new LineAssociationPainter(
					mPaintersMap.get(association.getNodeFrom()),
					mPaintersMap.get(association.getNodeTo()));
			association.paint(painter);
			FxUtil.runOnFx(new Runnable() {

				@Override
				public void run() {
					mMainGroup.getChildren().add(0, painter.getContent());
				}
			});
		}
		return mMainGroup;
	}
}
